/// <reference path="../declare/dec.d.ts"/>
import getAction, {
    getActionOfImportPhone
} from "../action/action.ts"
import {
    appData
} from "./appData.ts"
/*echarts 声明*/
declare let echarts: {
    init(id): ChartEntityItf
};

interface ChartEntityItf {
    setOption(option: {}): void
    resize()
    showLoading(): void
    hideLoading(): void
}
interface ChartDomItf {
    //id:string
    chartEntity: ChartEntityItf
    initialized: boolean
    paint(option: {}): void
}

function noData(parent: HTMLElement) {
    var p = document.createElement('p');
    p.innerHTML = '未查询到相关数据';
    $(p).css({
        fontWeight: 'bold',
        'text-align': 'center',
        padding: '20px',
        margin: '0px'
    })
    parent.appendChild(p)
}
class Chart implements ChartDomItf {
    initialized: boolean
    constructor(private id: string, public chartEntity: ChartEntityItf) {
        this.initialized = false
    }
    paint(option: {}) {
        this.chartEntity.setOption(option)
    }
    resize(): this {
        this.chartEntity.resize();
        return this
    }
    showLoading(): this {
        this.chartEntity.showLoading();
        return this
    }
    hideLoading(): this {
        this.chartEntity.hideLoading();
        return this
    }
}

function chartFactory(id: string): Chart {
    return new Chart(id, echarts.init(document.getElementById(id)))
}


interface AjaxCode {
    code: number
}
/*车主性别*/
let sexChart = chartFactory('Sex');
let sexAction = getAction('getsex');

// window.sexChart=sexChart;
export function handleSexChart(): void {
    sexChart.resize().showLoading();
    sexAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie
    }, {
            success(text) {
                if (text.code === 0) {
                    let option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: "{a} <br/>{b}: {c} ({d}%)"
                        },
                        legend: {
                            orient: 'vertical',
                            x: 'left',
                            // data: ['男性用户', '女性用户', '未知']
                        },
                        series: [{
                            name: '性别比例',
                            type: 'pie',
                            radius: ['50%', '70%'],
                            avoidLabelOverlap: false,
                            label: {
                                normal: {
                                    show: false,
                                    position: 'center'
                                },
                                emphasis: {
                                    show: true,
                                    textStyle: {
                                        fontSize: '30',
                                        fontWeight: 'bold'
                                    }
                                }
                            },
                            labelLine: {
                                normal: {
                                    show: false
                                }
                            },
                            data: [{
                                value: text.male,
                                name: '男性用户',
                                itemStyle: {
                                    normal: {
                                        color: '#5CB6F9'
                                    }
                                }
                            }, {
                                    value: text.female,
                                    name: '女性用户',
                                    itemStyle: {
                                        normal: {
                                            color: '#FFAE3B'
                                        }
                                    }
                                }, {
                                    value: text.unknow,
                                    name: '未知',
                                    itemStyle: {
                                        normal: {
                                            color: 'gray'
                                        }
                                    }
                                },]
                        }]
                    };
                    let total = text.male + text.female + text.unknow;
                    $('#male-num').text(Math.round(text.male / total * 10000) / 100 + '%');
                    $('#female-num').text(Math.round(text.female / total * 10000) / 100 + '%');
                    $('#unknow-num').text(Math.round(text.unknow / total * 10000) / 100 + '%');
                    sexChart.hideLoading().paint(option);
                }
            },
            error() {
                console.warn('boom');
                // console.trace();
                // sexChart.paint({})
            }
        })
}

/*家庭状况信息*/
let familyconditionChart = chartFactory('Familycondition');
let familyconditionAction = getAction('familycondition');

export function handleFamilyconditionChart(): void {
    familyconditionChart.resize().showLoading()
    familyconditionAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie
    }, {
            success(text) {
                let option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: "{a} <br/>{b}: {c} ({d}%)"
                    },
                    legend: {
                        orient: '2',
                        x: 'left',
                        // data: ['育有子女', '未知']
                    },
                    series: [{
                        name: '家庭状况',
                        type: 'pie',
                        radius: ['50%', '70%'],
                        avoidLabelOverlap: false,
                        label: {
                            normal: {
                                show: false,
                                position: 'center'
                            },
                            emphasis: {
                                show: true,
                                textStyle: {
                                    fontSize: '30',
                                    fontWeight: 'bold'
                                }
                            }
                        },
                        labelLine: {
                            normal: {
                                show: false
                            }
                        },
                        data: [{
                            value: text.baby,
                            name: '育有子女',
                            itemStyle: {
                                normal: {
                                    color: '#F6D234'
                                }
                            }
                        }, {
                                value: text.unknow,
                                name: '未知',
                                itemStyle: {
                                    normal: {
                                        color: '#58A2DF'
                                    }
                                }
                            },]
                    }]
                }
                let total = text.baby + text.unknow;
                $('#have-num').text(Math.round(text.baby / total * 10000) / 100 + '%');
                $('#no-num').text(Math.round(text.unknow / total * 10000) / 100 + '%');
                familyconditionChart.hideLoading().paint(option);

            },
            error() {

                // familyconditionChart.paint(option)
            }
        })

}

// handleFamilycondition();


/*车主常驻地区域*/
let homepositionChart = chartFactory('Homeposition');
let homepositionAction = getAction('getLocation?action=homeposition');

interface Point {
    count: number,
    lat: number,
    lng: number
}
interface MapData extends AjaxCode {
    points: Point[],
    max: number
}

function magnify(max: number) {
    switch (true) {
        case max > 1100:
            return 5 / 11
        case max > 1000:
            return 0.5
        case max > 800:
            return 0.65
        case max > 600:
            return 5 / 6
        case max > 400:
            return 5 / 4
        case max > 200:
            return 5 / 2
        default:
            return 1
    }
}
// window.homepositionChart=homepositionChart;
export function handleHomepositionChart(): void {
    homepositionChart.resize().showLoading()
    homepositionAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie
    }, {
            success(data: MapData) {
                if (data.code === 0) {
                    let magnifyer = magnify(data.max);
                    let mapData = [];
                    for (let p of data.points) {
                        mapData.push({
                            value: [p.lng, p.lat, Math.round(p.count * magnifyer)]
                        })
                    }
                    let option = {
                        title: {
                            // text: '车主常驻地',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item'
                        },
                        bmap: {
                            center: [104.114129, 37.550339],
                            zoom: 5,
                            roam: true,
                            mapStyle: {
                                styleJson: [{
                                    'featureType': 'water',
                                    'elementType': 'all',
                                    'stylers': {
                                        'color': '#d1d1d1'
                                    }
                                }, {
                                        'featureType': 'land',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#f3f3f3'
                                        }
                                    }, {
                                        'featureType': 'railway',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'highway',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#fdfdfd'
                                        }
                                    }, {
                                        'featureType': 'highway',
                                        'elementType': 'labels',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'arterial',
                                        'elementType': 'geometry',
                                        'stylers': {
                                            'color': '#fefefe'
                                        }
                                    }, {
                                        'featureType': 'arterial',
                                        'elementType': 'geometry.fill',
                                        'stylers': {
                                            'color': '#fefefe'
                                        }
                                    }, {
                                        'featureType': 'poi',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'green',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'subway',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'manmade',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#d1d1d1'
                                        }
                                    }, {
                                        'featureType': 'local',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#d1d1d1'
                                        }
                                    }, {
                                        'featureType': 'arterial',
                                        'elementType': 'labels',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'boundary',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#fefefe'
                                        }
                                    }, {
                                        'featureType': 'building',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#d1d1d1'
                                        }
                                    }, {
                                        'featureType': 'label',
                                        'elementType': 'labels.text.fill',
                                        'stylers': {
                                            'color': '#999999'
                                        }
                                    }]
                            }
                        },
                        series: [{
                            name: '车主常住地',
                            type: 'scatter',
                            coordinateSystem: 'bmap',
                            data: mapData,
                            // data:[{
                            //     value:[100,100,500]
                            // }],
                            symbolSize: function (val) {
                                return val[2] / 10;
                            },
                            label: {
                                normal: {
                                    formatter: '{b}',
                                    position: 'right',
                                    show: false
                                },
                                emphasis: {
                                    show: true
                                }
                            },
                            itemStyle: {
                                normal: {
                                    color: 'purple'
                                }
                            }
                        }]
                    };
                    homepositionChart.hideLoading().paint(option)
                }

            },
            error() { }
        })
}

/*车主工作地区域*/
let workpositionChart = chartFactory('Workposition');
let workpositionAction = getAction('getLocation?action=workposition');

export function handleWorkpositionChart(): void {
    workpositionChart.resize().showLoading()
    workpositionAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie
    }, {
            success(data: MapData) {
                if (data.code === 0) {
                    let magnifyer = magnify(data.max)
                    let mapData = [];
                    for (let p of data.points) {
                        mapData.push({
                            value: [p.lng, p.lat, Math.round(p.count * magnifyer)]
                        })
                    }
                    let option = {
                        title: {
                            // text: '车主工作地',
                            left: 'center'
                        },
                        tooltip: {
                            trigger: 'item'
                        },
                        bmap: {
                            center: [104.114129, 37.550339],
                            zoom: 5,
                            roam: true,
                            mapStyle: {
                                styleJson: [{
                                    'featureType': 'water',
                                    'elementType': 'all',
                                    'stylers': {
                                        'color': '#d1d1d1'
                                    }
                                }, {
                                        'featureType': 'land',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#f3f3f3'
                                        }
                                    }, {
                                        'featureType': 'railway',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'highway',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#fdfdfd'
                                        }
                                    }, {
                                        'featureType': 'highway',
                                        'elementType': 'labels',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'arterial',
                                        'elementType': 'geometry',
                                        'stylers': {
                                            'color': '#fefefe'
                                        }
                                    }, {
                                        'featureType': 'arterial',
                                        'elementType': 'geometry.fill',
                                        'stylers': {
                                            'color': '#fefefe'
                                        }
                                    }, {
                                        'featureType': 'poi',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'green',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'subway',
                                        'elementType': 'all',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'manmade',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#d1d1d1'
                                        }
                                    }, {
                                        'featureType': 'local',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#d1d1d1'
                                        }
                                    }, {
                                        'featureType': 'arterial',
                                        'elementType': 'labels',
                                        'stylers': {
                                            'visibility': 'off'
                                        }
                                    }, {
                                        'featureType': 'boundary',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#fefefe'
                                        }
                                    }, {
                                        'featureType': 'building',
                                        'elementType': 'all',
                                        'stylers': {
                                            'color': '#d1d1d1'
                                        }
                                    }, {
                                        'featureType': 'label',
                                        'elementType': 'labels.text.fill',
                                        'stylers': {
                                            'color': '#999999'
                                        }
                                    }]
                            }
                        },
                        series: [{
                            name: '车主工作地',
                            type: 'scatter',
                            coordinateSystem: 'bmap',
                            data: mapData,
                            // data:[{
                            //     value:[100,100,500]
                            // }],
                            symbolSize: function (val) {
                                return val[2] / 10;
                            },
                            label: {
                                normal: {
                                    formatter: '{b}',
                                    position: 'right',
                                    show: false
                                },
                                emphasis: {
                                    show: true
                                }
                            },
                            itemStyle: {
                                normal: {
                                    color: 'purple'
                                }
                            }
                        }]
                    };
                    workpositionChart.hideLoading().paint(option)
                }

            },
            error() { }
        })
}


/*四大垂直媒体*/
interface VerticalmediaData extends AjaxCode {
    autohome: number
    yiche: number
    pcauto: number
    xcar: number
}
let verticalmediaChart = chartFactory('Verticalmedia');
let verticalmediaAction = getAction('verticalmedia');

function rv(name, data) {
    $('#' + name).text(data[name])
}
export function handleVerticalmediaChart(): void {
    verticalmediaChart.resize().showLoading();
    verticalmediaAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie,
        year: appData.Year,
        month: appData.Month
    }, {
            success(data: VerticalmediaData) {
                if (data.code === 0) {
                    let option = {
                        color: ['#F3AA17'],
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                            }
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: [{
                            type: 'category',
                            data: ['汽车之家', '易车网', '太平洋汽车网', '爱卡汽车'],
                            axisTick: {
                                alignWithLabel: true
                            },
                            axisLine: {
                                lineStyle: {
                                    color: 'white'
                                }
                            }
                        }],
                        yAxis: [{
                            type: 'value',
                            axisLine: {
                                lineStyle: {
                                    color: 'white'
                                }
                            }
                        }],
                        series: [{
                            name: '直接访问',
                            type: 'bar',
                            barWidth: '60%',
                            data: [data.autohome, data.yiche, data.pcauto, data.xcar]
                        }]
                    };

                    rv('autohome', data);
                    rv('yiche', data);
                    rv('pcauto', data);
                    rv('xcar', data)
                    verticalmediaChart.hideLoading().paint(option)
                }
            },
            error() { }
        })
}


/*十大最受欢迎汽车网站*/
interface SingleWeb {
    name: string
    pv: number
    label: string
}
interface WebtopData extends AjaxCode {
    webtop: SingleWeb[]
}
let webtopChart = document.getElementById('Webtop');
let webtopAction = getAction('webtop');
export function handleWebtopChart(): void {
    webtopAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie,
        year: appData.Year,
        month: appData.Month
    }, {
            success(data: WebtopData) {
                // data.webtop.length=0
                if (data.code === 0) {
                    let topOne = document.getElementById('web-top-one'),
                        leftNine = document.getElementById('web-left-nine');
                    topOne.innerHTML = '', leftNine.innerHTML = '';

                    for (let web of data.webtop) {
                        let img = document.createElement('img'),
                            imgWrap = document.createElement('div');
                        img.setAttribute('src', `../images/logo/${web.label}.png`);
                        $(imgWrap).css({
                            width: '33%',
                            display: 'inline-block',
                            vertical: 'top',
                            'text-align': 'center'
                        }).append(img)
                        web.pv === 1 ? (topOne.appendChild(imgWrap)) : (leftNine.appendChild(imgWrap))
                    }
                    if (!data.webtop.length) noData(webtopChart)
                } else {

                }
            },
            error(data) { }
        })
}

/*十大最受欢迎App*/
interface SingleApp extends SingleWeb { }

interface ApptopData extends AjaxCode {
    apptop: SingleApp[]
}
let apptopChart = document.getElementById('Apptop');
let apptopAction = getAction('apptop');
export function handleApptopChart(): void {
    apptopAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie,
        year: appData.Year,
        month: appData.Month
    }, {
            success(data: ApptopData) {
                if (data.code === 0) {
                    let topOne = document.getElementById('app-top-one'),
                        leftNine = document.getElementById('app-left-nine');
                    topOne.innerHTML = '', leftNine.innerHTML = '';

                    for (let web of data.apptop) {
                        //图片处理
                        let img = document.createElement('img'),
                            imgWrap = document.createElement('div');
                        img.setAttribute('src', `../images/logo/${web.label}.png`);
                        $(imgWrap).css({
                            width: '33%',
                            display: 'inline-block',
                            vertical: 'top',
                            'text-align': 'center'
                        }).append(img)
                        web.pv === 1 ? (topOne.appendChild(imgWrap)) : (leftNine.appendChild(imgWrap))
                    }
                    if (!data.apptop.length) noData(apptopChart)
                }
            },
            error(data) { }
        })
}

/*获取最受欢迎十大车系*/

interface Cartype {
    name: string
    concer: number
}

interface CartopData extends AjaxCode {
    cartype: Cartype[]
}

let cartop = document.getElementById('Cartop');
let cartopAction = getAction('cartop');
export function handleCartopChart(): void {
    cartopAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie,
        year: appData.Year,
        month: appData.Month
    }, {
            success(data: CartopData) {
                if (data.code === 0) {
                    // console.log()
                    let fragment = document.createDocumentFragment();
                    for (let car of data.cartype) {
                        // let carDom=document.createElement('')
                        let carDom = document.createElement('div');
                        $(carDom).addClass('cartop-car');
                        carDom.innerHTML = `<img src="" alt="">
                            <div class="car-content">
                                <p class="car-name">${car.name}</p>
                                <div style="width:100%;border-top:3px solid #c7c3c3"><div style="border-top:3px solid #FFAE3B;width:80%;margin-top:-3px"></div></div>
                                <p class="car-concer">${car.concer}</p>
                                <p>/月关注数</p>
                            </div>`;
                        fragment.appendChild(carDom);
                    }

                    cartop.innerHTML = ''
                    cartop.appendChild(fragment)
                    if (!data.cartype.length) noData(cartop)
                }
                console.log(data)
            },
            error(data) { }
        })
}

/*车型对比*/

interface ComparisonsData extends CartopData { }

let compare = document.getElementById('Comparisons');
let comparisonsAction = getAction('comparisons');
export function handleComparisonsChart(): void {
    comparisonsAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie,
        year: appData.Year,
        month: appData.Month
    }, {
            success(data: ComparisonsData) {
                if (data.code === 0) {
                    // console.log()

                    let fragment = document.createDocumentFragment();
                    for (let car of data.cartype) {
                        // let carDom=document.createElement('')
                        let carDom = document.createElement('div');
                        $(carDom).addClass('cartop-car');
                        carDom.innerHTML = `<img src="" alt="">
                        <div class="car-content">
                            <p class="car-name">${car.name}</p>
                            <div style="width:100%;border-top:3px solid #c7c3c3"><div style="border-top:3px solid #FFAE3B;width:80%;margin-top:-3px"></div></div>
                            <p class="car-concer">${car.concer}</p>
                            <p>/月关注数</p>
                        </div>`;
                        fragment.appendChild(carDom);
                    }
                    // let cartop = document.getElementById('Comparisons');
                    compare.innerHTML = ''
                    compare.appendChild(fragment)
                    if (!data.cartype.length) noData(compare)
                }
                console.log(data)
            },
            error(data) { }
        })
}


/*车主兴趣*/
interface Taste {
    name: string
    ratio: number
}
interface HobbiesData extends AjaxCode {
    taste: Taste[]
}

function formatterLabel(param){
    return param.data*100+'%'
}
function formatterTooltip(param){
    console.log(param);
    return param
}

let hobbiesChart = chartFactory('Hobbies');
let hobbiesAction = getAction('hobbies');
export function handleHobbiesChart(): void {
    hobbiesChart.resize().showLoading();
    hobbiesAction.post({
        province_id: appData.Province_id,
        sessionid: appData.Cookie
    }, {
            success(data: HobbiesData) {
                if (data.code === 0) {

                    let legendData = [],
                        seriesData = [];
                    for (let taste of data.taste) {
                        legendData.push(taste.name);
                        seriesData.push({
                            name: taste.name,
                            type: 'bar',
                            stack: '比例',
                            label: {
                                normal: {
                                    show: true,
                                    position: 'top',
                                    formatter:formatterLabel
                                }
                            },
                            data: [taste.ratio.toFixed(5)]
                        })
                    }
                    let option = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                            },
                            // formatter:formatterTooltip
                        },
                        legend: {
                            data: legendData
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'value'
                        },
                        yAxis: {
                            type: 'category',
                            data: ['车主兴趣爱好']
                        },
                        series: seriesData
                    };

                    hobbiesChart.hideLoading().paint(option)
                }
            },
            error() {

            }
        })
}


let uploadAction = getActionOfImportPhone('importphone')


export function upload(form: FormData,modal?:HTMLElement) {
    // var formdata = new FormData(<HTMLFormElement>document.getElementById('upload-form'));
    uploadAction.post(form, {
        success(data) {
            if (data.code === 0) {
                // location.assign('chart.html')
                alert('上传成功');
            } else {
                alert('上传失败')
            }
            modal && $(modal).modal('hide')
        },
        error() {
            alert('上传失败')
        }
    })
}